﻿using System;
using System.IO;

namespace System.Net.DnsToolkit.Packet.Lazy {
    public class BufferReader : IBufferReader {

        private int _base {get; set;}
        private long _size {get; set;}
        private long _end {
            get {
                return _base + _size;
            }
        }

        private Stream _stream {get; set;}

        public BufferReader(Stream stream) {

            if (!stream.CanSeek) {
                throw new NotSupportedException("stream seek");
            }
            _stream = stream;
            _size = stream.Length;
        }

        public ushort Read16(int offset) {

            var roffset = _base + offset;
            var rend = roffset + sizeof(ushort);
            if (rend > _end) {
                throw new ArgumentOutOfRangeException("offset");
            }

            var bs = new byte[sizeof(ushort)];

            lock (_stream) {
                if (_stream.Position != roffset) {
                    _stream.Seek(roffset, SeekOrigin.Begin);
                }
                _stream.Read(bs, 0, bs.Length);
            }
            return (ushort)(
                bs[1] << 0
                | bs[0] << 8);

      
        }

        public byte Read8(int offset) {

            var roffset = _base + offset;
            var rend = roffset + sizeof(byte);
            if (rend > _end) {
                throw new ArgumentOutOfRangeException("offset");
            }

            var bs = new byte[sizeof(byte)];
            lock (_stream) {
                if (_stream.Position != roffset) {
                    _stream.Seek(roffset, SeekOrigin.Begin);
                }
                _stream.Read(bs, 0, bs.Length);
            }
            return (byte)(bs[0]);
        }
    }
}
